/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package zooi;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.swing.JOptionPane;

/**
*
* @author joopblankert
*/
public class BabbelClient {

   PrintWriter schrijf;
   BufferedReader lees;
   String adres = "localhost";
   int poort = 4444;
   Socket client;
   String tekst, verzenden;

   public BabbelClient() {
       verbindserver();

       if (client.isConnected()) {
           maakvariabelen();
           communiceerserver();
       }
   }

   public static void main(String[] args) {
       new BabbelClient();
   }

   void communiceerserver() {
       new Thread(new Ontvang()).start();

       while (client.isConnected()) {

           zend(dialog());
       }
   }

   void zend(String tekst) {
       if (tekst != null) {
           schrijf.println(tekst);
       //loggen("CLIENT: verzenden = " + tekst);
       } else {
           schrijf.println("XXX");
           loggen("CLIENT: gestopt");
           System.exit(0);
       }
   }

   void verbindserver() {
       try {
           client = new Socket(adres, poort);
           //   verbonden = true;
           loggen("CLIENT: verbonden met server");
       } catch (Exception e) {
           loggen("CLIENT: server niet beschikbaar");
           message("de server is niet beschikbaar");
           System.exit(0);
       }
   }

   void maakvariabelen() {
       try {
           lees = new BufferedReader(new InputStreamReader(client.getInputStream()));
           schrijf = new PrintWriter(client.getOutputStream(), true);
       } catch (Exception e) {
       }
   }

   void loggen(String tekst) {
       System.out.println(tekst);
   }

   String dialog() {
       return KeyBoard.getLine();
   }

   void message(String tekst) {
       JOptionPane.showMessageDialog(null, tekst, "CLIENT", 2);
   }

   class Ontvang implements Runnable {

       String readLine = "";

       public void run() {
           try {
               while ((readLine = lees.readLine()) != null) {
                   System.err.println(readLine);
               }
           } catch (Exception e) {
           }
       }
   }
}

class KeyBoard {

   static String getLine() {
       String inputLine = "";
       BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
       try {
           inputLine = is.readLine();
       } catch (Exception ignored) {
       }
       return inputLine;

   }
}